package com.clickpaas.governmentcloud.monitor;

import com.clickpaas.governmentcloud.common.ConstantExt;
import com.clickpaas.governmentcloud.config.AutoLoadConfig;
import com.clickpaas.governmentcloud.entity.policyEntity.MatchingResults;
import com.clickpaas.governmentcloud.entity.policyEntity.PolicyEntity;
import com.clickpaas.governmentcloud.service.policymatchextservice.MatchExtMainService;
import com.clickpaas.governmentcloud.service.policyservice.PolicyService;
import com.clickpaas.governmentcloud.thread.BatchDealMatchThread;
import com.clickpaas.governmentcloud.thread.BatchQueryMatchResultCallable;
import com.clickpaas.governmentcloud.utils.policycondcalutils.OpenCsvUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.entity.ContentType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

@Slf4j
@Service
public class FileAnalysis {
    @Resource
    private MatchExtMainService matchExtMainService;
    @Resource
    private PolicyService policyService;

    public void fileToPolicyEntity(File file) {

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            log.info("文件读取错误：【{}】",e);
        }
        MultipartFile multipartFile = null;
        try {
            multipartFile = new MockMultipartFile(file.getName(), file.getName(),
                    ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
        } catch (IOException e) {
            log.info("文件转换错误：【{}】",e);
        }
        OpenCsvUtil openCsvUtil = new OpenCsvUtil();
        List<PolicyEntity> csvData = openCsvUtil.getCsvData(multipartFile, PolicyEntity.class);
        if (csvData.size()>0){
            batchTemplateMatchExt(csvData);
            List<MatchingResults> matchingResults = batchQueryMatchResult(csvData);
            batchTemplateExport(matchingResults);
        }
    }

    //批量数据精确匹配
    private void batchTemplateMatchExt(List<PolicyEntity> policyEntityList){
        Map<Long,Integer> map = new HashMap<Long,Integer>();
        int pcount = Runtime.getRuntime().availableProcessors();
        ExecutorService executorService = Executors.newFixedThreadPool(pcount);
        map.put(ConstantExt._PCOUNT,pcount);
        try {
            for(int i=0;i<pcount;i++){
                int finalI = i;
                executorService.submit(() -> {
                    BatchDealMatchThread batchDealMatchThread = new BatchDealMatchThread(policyEntityList, map, matchExtMainService);
                    map.put(batchDealMatchThread.getId(), finalI);
                });
            }
        }catch (Exception e){
            log.info("批量数据精确匹配报错：【{}】",e);
        }finally {
            executorService.shutdown();
        }
    }

    private List<MatchingResults> batchQueryMatchResult(List<PolicyEntity> policyEntityList){
        ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        ArrayList<Future<List<MatchingResults>>> futures = new ArrayList<>();
        ArrayList<MatchingResults> returnCodeList = new ArrayList<>();
        try {
            for (int i = 0; i < policyEntityList.size(); i++) {
                BatchQueryMatchResultCallable t = new BatchQueryMatchResultCallable(policyEntityList.get(i),policyService);
                Future<List<MatchingResults>> submit = pool.submit(t);
                futures.add(submit);
            }
        }catch (Exception e){
            log.info("批量匹配线程异常：【{}】",e);
        }finally {
            pool.shutdown();
        }
        for (Future<List<MatchingResults>> f : futures) {
            try {
                List<MatchingResults> matchingResults = f.get();
                if (null == matchingResults)continue;
                returnCodeList.addAll(matchingResults);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (returnCodeList.size()>0){
            return returnCodeList;
        }
        return null;
    }

    //匹配结果批量导出
    private void batchTemplateExport(List<MatchingResults> policyEntityList){
        try {
            OpenCsvUtil openCsvUtil = new OpenCsvUtil();
            openCsvUtil.generateCsvFile(policyEntityList, AutoLoadConfig.EXPORT_PATH+AutoLoadConfig.EXPORT_FILE_NAME, AutoLoadConfig.HEADER_MATCH);
            //openCsvUtil.readCsvFileStream("exportResults.csv", response);
        } catch (Exception e) {
            log.error("EXPORT ERROR", e);
        }
    }

}
